//
//  QBMFImagePickerController.m
//  QBImagePickerControllerDemo
//
//  Created by Michael Fan on 14/11/7.
//  Copyright (c) 2014年 Katsuma Tanaka. All rights reserved.
//

#import "QBMFImagePickerController.h"

#import "QBImagePickerController.h"
#import "QBAssetsCollectionViewController.h"
#import "QBAssetsCollectionViewLayout.h"

ALAssetsFilter * ALAssetsFilterFromQBImagePickerControllerFilterType(QBImagePickerControllerFilterType type) {
    switch (type) {
        case QBImagePickerControllerFilterTypePhotos:
            return [ALAssetsFilter allPhotos];
            break;
            
        case QBImagePickerControllerFilterTypeVideos:
            return [ALAssetsFilter allVideos];
            break;
    }
}

@interface QBMFImagePickerController ()

@property (nonatomic, strong, readwrite) ALAssetsLibrary *assetsLibrary;
@property (nonatomic, copy, readwrite) NSArray *assetsGroups;
@property (nonatomic, copy) NSArray *groupTypes;

@end

@implementation QBMFImagePickerController

+ (BOOL)isAccessible
{
    return ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary] &&
            [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]);
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        // Property settings
        self.view.backgroundColor = [UIColor whiteColor];

        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
            self.interactivePopGestureRecognizer.delegate = self;
        }
        
        self.selectedAssetURLs = [NSMutableArray array];
        self.groupTypes = @[
                            @(ALAssetsGroupSavedPhotos),
                            @(ALAssetsGroupEvent),
                            @(ALAssetsGroupAlbum)
                            ];
        self.filterType = QBImagePickerControllerFilterTypePhotos;
        
        // Create assets library instance
        ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
        self.assetsLibrary = assetsLibrary;
        
        [self loadAssetsGroupsWithTypes:self.groupTypes
                             completion:^(NSArray *assetsGroups) {
                                 self.assetsGroups = assetsGroups;
                                 
                                 QBImagePickerController *imagePickerController = [[QBImagePickerController alloc] init];
                                 imagePickerController.assetsGroups = self.assetsGroups;
                                 
                                 QBAssetsCollectionViewController *assetsCollectionViewController = [[QBAssetsCollectionViewController alloc] initWithCollectionViewLayout:[QBAssetsCollectionViewLayout layout]];
                                 
                                 ALAssetsGroup *assetsGroup = [self.assetsGroups objectAtIndex:[self.groupTypes indexOfObject:@(ALAssetsGroupSavedPhotos)]];
                                 assetsCollectionViewController.assetsGroup = assetsGroup;
                                 
                                 [self setViewControllers:[NSArray arrayWithObjects:imagePickerController,assetsCollectionViewController, nil]];
                                 
                             }];
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

#pragma mark - Managing Assets

- (void)loadAssetsGroupsWithTypes:(NSArray *)types completion:(void (^)(NSArray *assetsGroups))completion
{
    __block NSMutableArray *assetsGroups = [NSMutableArray array];
    __block NSUInteger numberOfFinishedTypes = 0;
    
    for (NSNumber *type in types) {
        __weak typeof(self) weakSelf = self;
        
        [self.assetsLibrary enumerateGroupsWithTypes:[type unsignedIntegerValue]
                                          usingBlock:^(ALAssetsGroup *assetsGroup, BOOL *stop) {
                                              if (assetsGroup) {
                                                  // Filter the assets group
                                                  [assetsGroup setAssetsFilter:ALAssetsFilterFromQBImagePickerControllerFilterType(weakSelf.filterType)];
                                                  
                                                  if (assetsGroup.numberOfAssets > 0) {
                                                      // Add assets group
                                                      [assetsGroups addObject:assetsGroup];
                                                  }
                                              } else {
                                                  numberOfFinishedTypes++;
                                              }
                                              
                                              // Check if the loading finished
                                              if (numberOfFinishedTypes == types.count) {
                                                  // Sort assets groups
                                                  NSArray *sortedAssetsGroups = [self sortAssetsGroups:(NSArray *)assetsGroups typesOrder:types];
                                                  
                                                  // Call completion block
                                                  if (completion) {
                                                      completion(sortedAssetsGroups);
                                                  }
                                              }
                                          } failureBlock:^(NSError *error) {
                                            //  NSLog(@"Error: %@", [error localizedDescription]);
                                          }];
    }
}

- (NSArray *)sortAssetsGroups:(NSArray *)assetsGroups typesOrder:(NSArray *)typesOrder
{
    NSMutableArray *sortedAssetsGroups = [NSMutableArray array];
    
    for (ALAssetsGroup *assetsGroup in assetsGroups) {
        if (sortedAssetsGroups.count == 0) {
            [sortedAssetsGroups addObject:assetsGroup];
            continue;
        }
        
        ALAssetsGroupType assetsGroupType = [[assetsGroup valueForProperty:ALAssetsGroupPropertyType] unsignedIntegerValue];
        NSUInteger indexOfAssetsGroupType = [typesOrder indexOfObject:@(assetsGroupType)];
        
        for (NSInteger i = 0; i <= sortedAssetsGroups.count; i++) {
            if (i == sortedAssetsGroups.count) {
                [sortedAssetsGroups addObject:assetsGroup];
                break;
            }
            
            ALAssetsGroup *sortedAssetsGroup = [sortedAssetsGroups objectAtIndex:i];
            ALAssetsGroupType sortedAssetsGroupType = [[sortedAssetsGroup valueForProperty:ALAssetsGroupPropertyType] unsignedIntegerValue];
            NSUInteger indexOfSortedAssetsGroupType = [typesOrder indexOfObject:@(sortedAssetsGroupType)];
            
            if (indexOfAssetsGroupType < indexOfSortedAssetsGroupType) {
                [sortedAssetsGroups insertObject:assetsGroup atIndex:i];
                break;
            }
        }
    }
    
    return [sortedAssetsGroups copy];
}

-(void)imagePickerCancel
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
    // Delegate
    if (self.QBMFDelegate && [self.QBMFDelegate respondsToSelector:@selector(imagePickerControllerDidCancel:)])
        [self.QBMFDelegate imagePickerControllerDidCancel:self];
}
-(void)imagePickerFinish:(NSArray *)aryPhotos
{
    if (aryPhotos) {
        //images数组
        if ([self.QBMFDelegate respondsToSelector:@selector(imagePickerController:didSelectPhtos:)]) {
            [self.QBMFDelegate imagePickerController:self didSelectPhtos:aryPhotos];
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    else
    {
        __block NSMutableArray *aryFinished = [NSMutableArray array];
        for (NSURL *selectedAssetURL in self.selectedAssetURLs) {
            [self.assetsLibrary assetForURL:selectedAssetURL
                                          resultBlock:^(ALAsset *asset) {
                                              // Add asset
                                              ALAssetRepresentation *rep = [asset defaultRepresentation];
                                              [aryFinished addObject:[UIImage imageWithCGImage:[rep fullScreenImage]]];
                                              if ([self.selectedAssetURLs count] == [aryFinished count]) {
                                                  //选择完成出栈
                                                  if ([self.QBMFDelegate respondsToSelector:@selector(imagePickerController:didSelectPhtos:)]) {
                                                      [self.QBMFDelegate imagePickerController:self didSelectPhtos:aryFinished];
                                                  }
                                                  [self dismissViewControllerAnimated:YES completion:nil];
                                              }
                                              
                                          } failureBlock:^(NSError *error) {
                                              
                                          }];
        }
    }
}

-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer == self.interactivePopGestureRecognizer) {
        return ([self.viewControllers count] < 3);
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
